import Request from 'luch-request'; //npm下载引入luch-request

// const api = import.meta.env.VITE_BASE_URL;

// import qs from 'qs'
const http = new Request({
  baseURL: import.meta.env.VITE_BASE_URL, //设置请求的base url
  timeout: 30000, //超时时长30秒,
  header: {
    'Content-Type': 'application/json;charset=UTF-8',
  },
});

//请求拦截器
http.interceptors.request.use(
  (config) => {
    // 可使用async await 做异步操作
    const token = uni.getStorageSync('token');
    if (token) {
      config.header['Authorization'] = 'Bearer ' + token;
    }

    if (config.method === 'POST') {
    }

    console.log({ config });
    return config;
  },
  (error) => {
    return Promise.resolve(error);
  },
);

// 响应拦截器
http.interceptors.response.use(
  (response) => {
    console.log({ response })
    const responseData = response.data;
    if (responseData.status === 401) {
      uni.clearStorageSync();
      uni.switchTab({
        url: '/pages/login/index',
      });
    } else if (responseData.status !== 200) {
      uni.showToast({
        title: response?.data?.msg || '请求失败',
        duration: 2000,
        icon: 'error',
      });
      return Promise.reject(responseData);
    } else {
      return responseData;
    }
  },
  (error) => {
    console.log({ error})
    //未登录时清空缓存跳转
    if (error.statusCode == 401) {
      uni.clearStorageSync();
      uni.switchTab({
        url: '/pages/login/index',
      });
    }

    const { errMsg } = error;

    uni.showToast({
      title: errMsg,
      duration: 2000,
    });
    return Promise.resolve(error);
  },
);
export default http;
